//商品管理
import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { ConfigProvider } from 'antd';
import zh_CN from 'antd/es/locale/zh_CN';
import { Input, Select, Space, Button, Form, Table, DatePicker, Switch, Image, Modal, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { ExclamationCircleFilled } from '@ant-design/icons';
import type { TableRowSelection } from 'antd/es/table/interface';
import './css/Promotion.css'
import { findGoods, deleteOne } from '../../../api/promotion';
//表格数据类型
interface DataType {
  id: number;//序号
  img: string;//图片
  name: string;//名称
  sernum: string;//货号
  price: any;//价格
  rec: string;//分类
  sell: number;//销量
  state: number//状态
  seat: number//位置

}
export default function Commodity() {
  const [ModalOpen, setModalOpen] = useState(false);//删除弹框
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [data, setData] = useState<DataType[]>();//装表格内容
  const [page, setPage] = useState(1)//页码
  const [pageSize, setPagesize] = useState(5)//一页几条
  const [count, setCount] = useState<number>()
  const location = useLocation()
  const [id, setID] = useState<number>() //id
  const [prid, setPrId] = useState<number>() //id
  //表格部分
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'id',
    },
    {
      title: '封面图',
      dataIndex: 'img',
      render: (_, record) => (
        <Image
          width={50}
          height={50}
        // src="https://img0.baidu.com/it/u=3007048469,3759326707&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1677690000&t=6631b97b2d291cb6ca173fa887f1ea71"
        />
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'name',
    },
    {
      title: '货号',
      dataIndex: 'sernum',
    },
    {
      title: '价格',
      dataIndex: 'price',
    },
    {
      title: '分类',
      dataIndex: 'rec',
    },
    {
      title: '销量',
      dataIndex: 'sell',
    },
    {
      title: '位置',
      dataIndex: 'seat',
    },
    {
      title: '是否上架',
      dataIndex: 'state',
      render: (_, record) => (
        <Switch defaultChecked onChange={onChange} />
      ),
    },
    {
      title: '操作',
      dataIndex: 'adds',
      render: (_, record) => (
        <Space size="middle">
          <Button id='del' onClick={() => showModal(record)} >删除</Button>
        </Space >
      ),
    },
  ];
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  //表格排序
  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  //获取页码
  const Change = (page: number, pageSize: number) => {
    console.log(page, pageSize);
    setPage(page)
    setPagesize(pageSize)
  }

  useEffect(() => {
    console.log('id', location.state.id);
    FindGoods()
  }, [page, pageSize])

  //获取促销商品的内容
  const FindGoods = () => {
    findGoods({
      id: location.state.id,
      num: page,
      size: pageSize,
    }).then(res => {
      console.log('获取参加促销列表', res);
      if (res.code == '200') {
        setData(res.data.goods)
        setCount(res.data.total)
      }
    }).catch(err => {
      console.log('失败', err);
    })
  }


  //时间状态
  const handleChange = (value: number) => {
    console.log(`selected`, value);
    findGoods({
      id: location.state.id,
      num: page,
      size: pageSize,
      sort: value
    }).then(res => {
      console.log('排序成功', res);
      if (res.code == '200') {
        setData(res.data.goods)
        setCount(res.data.total)
      }
    }).catch(err => {
      console.log('排序失败', err);
    })
    message.success('排序成功！')

  };
  //路由跳转
  const navigate = useNavigate()

  //点击跳转商品添加
  const add = () => {
    navigate('/home/promotion/AddCommodity', {
      state: {
        id: location.state.id
      }
    })
  }

  //返回上一页
  const goBackPage = () => {
    window.history.back()
  }

  //删除
  const showModal = (record: any) => {
    setModalOpen(true);
    console.log('OK', record);
    setID(record.id)
    setPrId(location.state.id)
  };

  const handleOk = () => {
    setModalOpen(false);
    deleteOne({
      pro: prid,
      id: id,
    }).then(res => {
      console.log('删除成功', res);
      if (res.code == '200') {
        FindGoods()
      }
    }).catch(err => {
      console.log('删除失败', err);
    })
    message.success('删除成功！')
  };

  const handleCancel = () => {
    setModalOpen(false);
  };


  //启动按钮
  const onChange = (checked: boolean) => {
    console.log(`switch to ${checked}`);
  };
  return (
    <div>
      <Space>
        <Button className='return' onClick={goBackPage}>返回</Button>
      </Space>
      {/* 标题 */}
      <p className="head">商品管理</p>
      {/* 操作部分 */}
      <div className='operate-wrap'>
        <div className='operate-left'>
        </div>
      </div>
      {/* 表格 */}
      <div className='table'>
        {/* 表格操作 */}
        <div className='operationTable'>
          {/* 排序 */}
          <Form>
            <Form.Item label='排序：' className='operate-left-item' name='state'>
              <Space wrap>
                <Select
                  onChange={handleChange}
                  style={{ width: 120 }}
                  allowClear
                  options={[{ value: '1', label: '销量顺序' }, { value: '2', label: '销量逆序' }, { value: '3', label: '上架时间顺序' }, { value: '4', label: '上架时间倒叙' }]}
                  className='drop'
                />
              </Space>
            </Form.Item>
          </Form>
          <Button className='add' onClick={add}>添加商品</Button>
        </div>
        <ConfigProvider locale={zh_CN}>
          <Table rowSelection={rowSelection} columns={columns} rowKey={item => item.id} dataSource={data} pagination={{
            position: ['bottomRight'],
            pageSizeOptions: [3, 5, 10, 15],
            showQuickJumper: true,
            showSizeChanger: true,
            onChange: Change,
            pageSize: pageSize,
            total: count,
          }} />
        </ConfigProvider>
      </div>
      {/* 删除内容 */}
      <Modal title="提示" open={ModalOpen} onOk={handleOk} onCancel={handleCancel} okText='确定' cancelText='取消'>
        <p>确定要删除该条数据吗？</p>
      </Modal>
    </div>
  )
}